﻿using Dapper;
using MKAdminCore.DTO.Web.BasicSetting;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.IService.Web.BasicSetting;
using MKAdminCore.Service.Web.Common;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using System.Linq;

namespace MKAdminCore.Service.Web.BasicSetting
{
    public class RoleInfoService : IRoleInfoService
    {
        /// <summary>
        /// 获取角色信息
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public PagingList<OperatorRoleInfo> List(GetRoleInfoListParameter parameter)
        {
            var list = new PagingList<OperatorRoleInfo>();

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(@"select RoleId,RoleName,StatusCode
	                                ,CONVERT(varchar(16), CreateTime, 120) CreateTime 
                                from dbo.OperatorRoleInfo ori with(nolock) 
                                Where ori.StatusCode = 0");

                var param = new DynamicParameters();
                if (!string.IsNullOrEmpty(parameter.RoleName))
                {
                    sql.AppendLine("And oi.RoleName Like '%'+@RoleName+'%'");
                    param.Add("@RoleName", parameter.RoleName);
                }

                string sortingSql = "Order By RoleId Desc";
                if (!string.IsNullOrEmpty(parameter.sortName) && !string.IsNullOrEmpty(parameter.sortOrder))
                {
                    sortingSql = $"Order By {parameter.sortName} {parameter.sortOrder}";
                }

                list = conn.QueryGetList<OperatorRoleInfo>(sql.ToString(), sortingSql, parameter.pageIndex, parameter.pageSize, param);

                return list;
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> Add(OperatorRoleInfoAddParam parameter, UserInfo userInfo)
        {
            var result = new HttpResponseResult() { Msg = "新增成功" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(@"
                                If Not Exists(Select 1 From dbo.OperatorRoleInfo with(nolock) 
                                            Where RoleName = @RoleName And StatusCode in(0,1))
                                Begin
                                    INSERT INTO [dbo].[OperatorRoleInfo]
                                           ([RoleName],[RoleDesc],[StatusCode],[UpdatorId]
                                             ,[UpdateTime],[CreatorId],[CreateTime],Remark)
                                     VALUES
                                           (@RoleName,'',0,@UpdatorId
                                             ,getdate(),@UpdatorId,getdate(),'')
                                     Select SCOPE_IDENTITY();
                                End
                                Else
                                Begin
                                    Select -1;
                                End
                                ");

                var param = new DynamicParameters();
                param.Add("@RoleName", parameter.RoleName, size: 20);
                param.Add("@UpdatorId", userInfo.OperatorId);
                param.Add("@CreatorId", userInfo.OperatorId);

                object _r = await conn.ExecuteScalarAsync(sql.ToString(), param);
                if (_r != null)
                {
                    int rRoleId = Convert.ToInt32(_r);
                    if (rRoleId == -1)
                    {
                        result.Code = (int)HttpResponseCode.OperateFail;
                        result.Msg = "角色名称已存在";
                    }
                    //角色管理
                    if (rRoleId > 0)
                    {
                        await updateRoleRightInfo(rRoleId, parameter.RightIds);
                    }
                }
                else
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = "新增失败";
                }
                return result;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> Edit(OperatorRoleInfoEditParam parameter, UserInfo userInfo)
        {
            var result = new HttpResponseResult() { Msg = "修改成功" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(@"Update [dbo].[OperatorRoleInfo]
                                 Set [RoleName] = @RoleName
                                     ,UpdatorId = @UpdatorId
                                     ,[UpdateTime] = getdate()
                                 Where RoleId = @RoleId");

                var param = new DynamicParameters();
                param.Add("@RoleId", parameter.RoleId);
                param.Add("@RoleName", parameter.RoleName, size: 20);
                param.Add("@UpdatorId", userInfo.OperatorId);

                int _r = await conn.ExecuteAsync(sql.ToString(), param);
                if (_r <= 0)
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = "修改失败";
                }
                //角色管理
                await updateRoleRightInfo(parameter.RoleId, parameter.RightIds);
                return result;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> Del(OperatorRoleInfoDelParam parameter, UserInfo userInfo)
        {
            var result = new HttpResponseResult() { Msg = "删除成功" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"Update [dbo].[OperatorRoleInfo]
                                  Set StatusCode = 2 ,UpdatorId = {userInfo.OperatorId},UpdateTime = GetDate()
                                  Where RoleId = {parameter.RoleId}");

                int _r = await conn.ExecuteAsync(sql.ToString());
                if (_r <= 0)
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = "删除失败";
                }
                return result;
            }
        }

        /// <summary>
        /// 获取角色权限集合
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> GetRight(OperatorRoleInfoGetRight parameter)
        {
            var result = new HttpResponseResult<List<OperatorRoleRightConfig>>()
            {
                Msg = "",
                Data = new List<OperatorRoleRightConfig>()
            };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"
                                select t1.RoleId,t1.RightId from dbo.OperatorRoleRightConfig t1 with(nolock)
                                left join dbo.OperatorRightInfo t2 with(nolock)
	                                on t1.RightId = t2.RightId
                                where t2.TypeCode = 1
                                      And RoleId = {parameter.RoleId}");

                var _r = await conn.QueryAsync<OperatorRoleRightConfig>(sql.ToString());

                result.Data = _r.ToList();
                return result;
            }
        }


        /// <summary>
        /// 更新角色权限
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private async Task<HttpResponseResult> updateRoleRightInfo(int roleId, List<int> rightIds)
        {
            var result = new HttpResponseResult() { Msg = "设置成功" };

            if (roleId > 0)
            {
                using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
                {
                    StringBuilder sql = new StringBuilder();
                    sql.AppendLine($@"delete from dbo.OperatorRoleRightConfig where RoleId = @RoleId");

                    var param = new DynamicParameters();
                    param.Add("@RoleId", roleId);

                    await conn.ExecuteAsync(sql.ToString(), param);

                    if (rightIds != null && rightIds.Count > 0)
                    {
                        var rightConfig = new List<OperatorRoleRightConfig>();
                        rightIds.ForEach((q) =>
                        {
                            rightConfig.Add(new OperatorRoleRightConfig()
                            {
                                RoleId = roleId,
                                RightId = q
                            });
                        });

                        StringBuilder sqlRoleRight = new StringBuilder();
                        sqlRoleRight.AppendLine($@"
                                    insert into dbo.OperatorRoleRightConfig(RoleId,RightId)
                                    values(@RoleId,@RightId)");
                        await conn.ExecuteAsync(sqlRoleRight.ToString(), rightConfig);
                    }
                }
            }
            return result;
        }
    }
}
